package middleware

import (
	"bytes"
	"gin/config"
	"gin/util/cryp"
	"io/ioutil"

	"strconv"
	"time"

	"gin/model/http_error"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func HeaderAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		if !config.Http.EncryptCheck {
			c.Next()
			return
		}
		type stru struct {
			Endata string `json:"endata" form:"endata"`
			Ents   string `json:"ents" form:"ents"`
		}

		var o stru
		c.ShouldBind(&o)

		if config.Http.TimestampCheck {
			if o.Ents == "" {
				panic(http_error.MissingParametersError)
			}

			timestamp := cryp.AesDecryptCBC(o.Ents, config.Base.Key.EncryptKey)
			if timestamp == "" {
				panic(http_error.NoAESKey)
			}

			ti, _ := strconv.ParseInt(timestamp, 10, 64)
			now := time.Now().Unix() - int64(config.Base.TimeZone.Time)

			if ti-20 > now || ti+20 < now {
				logrus.Error("非法请求 now=", now, "，ts=", ti, "，diff=", now-ti, "，path="+c.FullPath())
				panic(http_error.NotAllowed)
			}
		}

		if o.Endata == "" {
			panic(http_error.MissingParametersError)
		}

		str := cryp.AesDecryptCBC(o.Endata, config.Base.Key.EncryptKey)
		if str == "" {
			panic(http_error.NoAESKey)
		}

		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(str)))
		c.Next()
	}

}
